package com.dc.project.service.impl;

import com.alibaba.fastjson.JSON;
import com.dc.project.entity.bo.UserVolcengineBo;
import com.dc.project.entity.map.UserVolcengineMapVo;
import com.dc.project.entity.po.UserVolcengine;
import com.dc.project.entity.query.UserVolcengineQuery;
import com.dc.project.entity.vo.UserVolcengineVo;
import com.dc.project.mapper.UserVolcengineMapper;
import com.dc.project.service.UserVolcengineService;
import com.own.component.common.base.service.impl.AbstractBaseService;
import com.own.component.store.core.Store;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * UserVolcengineServiceImpl
 *
 * @author chenxueli
 * @date 2025-04-25 11:33:04
 */
@Slf4j
@Service
public class UserVolcengineServiceImpl extends AbstractBaseService<
        UserVolcengine,
        UserVolcengineBo,
        UserVolcengineVo,
        UserVolcengineMapVo,
        UserVolcengineQuery,
        UserVolcengineMapper
        > implements UserVolcengineService {

    @Resource
    private UserVolcengineMapper userVolcengineMapper;

    @Resource
    private Store<String> store;

    /**
     * 根据用户id去获取信息
     *
     * @param userId 用户id
     * @return 用户大模型配置
     */
    @Override
    public UserVolcengine getPoByUserId(Long userId) {
        var wrapper = lambdaQueryWrapper()
                .eq(UserVolcengine::getFkUserId, userId);
        return userVolcengineMapper.selectOne(wrapper);
    }

    /**
     * 根据用户id去获取信息
     *
     * @param userId 用户id
     * @return 用户大模型配置
     */
    @Override
    public UserVolcengineMapVo getByUserIdForCache(Long userId) {
        var cacheKey = "volc:config:" + userId;
        var text = store.value().get(cacheKey);
        if (StringUtils.isNotBlank(text)) {
            return JSON.parseObject(text, UserVolcengineMapVo.class);
        }
        var po = getPoByUserId(userId);
        if (po == null) {
            return null;
        }
        var vo = new UserVolcengineMapVo(po);
        // 存入缓存
        store.value().set(cacheKey, JSON.toJSONString(vo), Duration.ofDays(1));
        return vo;
    }

    /**
     * 根据用户id去清除缓存
     *
     * @param userId 用户id
     */
    @Override
    public void clearCacheByUserId(Long userId) {
        store.value().remove("volc:config:" + userId);
    }

}
